package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> findByCondition(String queryString) {
        List<Menu> menuList = menuDao.selectByCondision(queryString);
        return menuList;
    }

    @Override
    public List<Menu> findParentMenuList() {
        List<Menu> menuList = menuDao.findParentMenuList();
        Menu menu = new Menu();
        menu.setId(0);
        menu.setName("无");
        menuList.add(menu);
        return menuList;
    }

    @Override
    public Menu findById(Integer id) {
        Menu menu = menuDao.findById(id);
        if (menu.getParentMenuId() == null){
            menu.setParentMenuId(0);
        }
        return menu;
    }

    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    @Override
    public void edit(Menu menu) {
        menuDao.edit(menu);
    }

    @Override
    public void deleteById(Integer id) {
        List<Menu> menuList = menuDao.findChildrenByParentId(id);
        if (menuList != null && menuList.size() > 0){
            throw new RuntimeException("有关联的子菜单,不能删除");
        }
        List<Role> roleList = menuDao.findRolesByMenuId(id);
        if (roleList != null && roleList.size() > 0){
            throw new RuntimeException("有关联的用户权限,不能删除");
        }
        menuDao.deleteById(id);
    }

    @Override
    public List<Menu> validateName(String menuName) {
        List<Menu> menuList = menuDao.validateName(menuName);
        return menuList;
    }

    /**
     * 查询所有菜单，以树形二级结构返回
     * @return
     */
    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }
}
